import * as React from 'react';
import { withRouter, RouteComponentProps } from 'react-router';
import { Redirect } from 'react-router-dom';

import { Input, TextArea } from '../../../components/input';
import { Markdown } from '../../../components/markdown';
import { Button } from '../../../components/button';

import Apis from '../../../apis';

type PropsType = RouteComponentProps<{ postId?: string }> & {};

type PageState = 'LOADING' | 'LOADED' | 'SAVED';

type StatesType = {
  postId?: number;
  pageState: PageState;
  title: string;
  content: string;
};

class PostEditorPage extends React.Component<PropsType> {
  state: StatesType = {
    pageState: 'LOADING',
    title: '',
    content: '',
  };

  async componentDidMount() {
    const { postId } = this.props.match.params;
    if (postId === null || postId === undefined) {
      this.setState({ pageState: 'LOADED' });
    } else {
      await this.loadPost(+postId);
    }
  }

  loadPost = async (postId: number) => {
    this.setState({ pageState: 'LOADING' });
    const post = await Apis.Post.getPost(postId);
    this.setState({ postId: post.postId, title: post.title, content: post.content, pageState: 'LOADED' });
  };

  handleSave = async () => {
    const { postId, title, content } = this.state;
    const result = await Apis.Post.savePost({ postId, title, content, format: 'md' });
    this.setState({ postId: result.postId, pageState: 'SAVED' });
  };

  render() {
    const { postId, pageState, title, content } = this.state;
    switch (pageState) {
      case 'LOADING':
        return <div>加载中...</div>;
      case 'LOADED':
        return (
          <div style={{ padding: '1rem' }}>
            <Input value={title} onChange={(e) => this.setState({ title: e.target.value })} />
            <div style={{ display: 'flex' }}>
              <div style={{ width: '50%' }}>
                <TextArea rows={30} value={content} onChange={(e) => this.setState({ content: e.target.value })} />
              </div>
              <div style={{ width: '50%', background: 'whitesmoke' }}>
                <Markdown md={content} />
              </div>
            </div>
            <Button onClick={this.handleSave}>保存</Button>
          </div>
        );
      case 'SAVED':
      default:
        return <Redirect to={`/p/${postId}`} />;
    }
  }
}

export default withRouter(PostEditorPage);
